//
//  ChooseProTreeVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2024/11/5.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
import EmptyDataSet_Swift

class ChooseProTreeVC: ZyaChooseProductVC {
    
    var goodArray = [GoodTreeNode]()
   var itemArray = [ZyaFOGoodTModel]()
    var selectMark:[(Int,GoodTreeNode)?] = [nil,nil,nil,nil,nil,nil,nil,nil,nil,nil]
    var selectDeepIndex = -1  // -1 全部
    var showingGoodsIndex:Int? = nil // 目前展示商品的层级
    var showNode: GoodTreeNode?
    func arrreset() {
        selectMark = [nil,nil,nil,nil,nil,nil,nil,nil,nil,nil]
        selectDeepIndex = -1
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.configClassification()
        self.network()
        
        
    }
    override func network() {
        var groupid = ""
        if let groupx = getGroupInfo() {
            groupid = groupx.s_group_id.unwrap
        }
            KSNetwork.shared.doRequest(API.queryGoodsIndustryGroup(s_group_id: groupid, s_org_id: s_orgid)) { (data:BaseResult<GoodTreeNode>) in
                if data.flag == TRUE {
                    if let infos = data.infoArrCombine {
                        self.goodArray = infos
                        self.tableView.reloadData()
                        self.tableView.mj_header?.endRefreshing()
                    }
                }
            }
        
        
        
    }
    func getGoods(model:GoodTreeNode) {
        KSNetwork.shared.doRequest(API.queryGoodsByIndustryGroup(s_goods_groups_tree_id: model.id_key.unwrap, s_org_id: s_orgid,s_client_id: clientid)) { (data:BaseResult<ZyaFOGoodTModel>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    self.itemArray = infos
                    self.configZyaClaBtnView()
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func configClassification() {
  
        claBgCollectionV.selectItemClo = { inp in
            KSLog("ppp")
            KSLog(inp.row)
            KSLog(self.showingGoodsIndex)
            KSLog("111")
            
            if (inp.row - 1) != self.showingGoodsIndex {
                self.showingGoodsIndex = nil
          
                self.selectDeepIndex = inp.row - 1
                self.configZyaClaBtnView()
                self.tableView.reloadData()
            }
            
       
            
        }
        self.tableView.tableHeaderView = claBgCollectionV
        self.configZyaClaBtnView()
    }
    func configZyaClaBtnView() {
        
        for i in 0..<self.selectMark.count {
            if i > self.selectDeepIndex {
                self.selectMark[i] = nil
            }
        }
        
        for (_, mark) in self.selectMark.enumerated() {
            if let node = mark?.1 {
                showNode = node
            } else {
                break
            }
        }
         

        let titles = ["全部"] + self.selectMark.compactMap { $0?.1.s_name }
        claBgCollectionV.dataArray = titles
        var widths = [Int]()
        for item in titles {
            let w = baseClaWidth + item.count * 12
            widths.append(w)

        }
        claBgCollectionV.maxlengths = widths

        
        claBgCollectionV.collectionView.reloadData()
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: ZyaChooseProCell.identifier, for: indexPath) as? ZyaChooseProCell else {
            fatalError()
        }
        if self.showingGoodsIndex.isSome {
            let model = self.itemArray[indexPath.row]
            cell.setLastNodeType(with: model)
            
            // 点击收藏 事件
            cell.markClosure = { [indexPath] in
                
             
                        let sm = self.itemArray[indexPath.row].sMark.unwrap
                        self.itemArray[indexPath.row].sMark = (sm == "1") ? "0" : "1"
                        self.setMarkNetwork(id: self.itemArray[indexPath.row].sGoodsId.unwrap, mark: self.itemArray[indexPath.row].sMark.unwrap)
                        self.tableView.reloadData()
                    
                 
                
            }
        } else {
            var model:GoodTreeNode!
            if self.selectDeepIndex == -1 {
                model = self.goodArray[indexPath.row]
            } else {
                model = showNode?.children[indexPath.row]
                
                
            }
//            else if self.selectDeepIndex == 0 {
//                let indd0 = self.selectMark[0]!.0
//                model = self.goodArray[indd0].children[indexPath.row]
//
//            } else if self.selectDeepIndex == 1 {
//                let indd0 = self.selectMark[0]!.0
//                let indd1 = self.selectMark[1]!.0
//
//                model = self.goodArray[indd0].children[indd1].children[indexPath.row]
//
//            }
            
            cell.setSuperType(with: model.s_name.unwrap)
            
                
               
        }
       
     
        
        

        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.showingGoodsIndex.isSome {
          

           return self.itemArray.count
        } else {
            if self.selectDeepIndex == -1 {
                return self.goodArray.count
            } else {
                return showNode?.children.count ?? 0
            }
//            else if self.selectDeepIndex == 0 {
//                let indd = self.selectMark[0]!.0
//                return self.goodArray[indd].children.count
//            }  else if self.selectDeepIndex == 1 {
//                let indd0 = self.selectMark[0]!.0
//                let indd1 = self.selectMark[1]!.0
//
//                return self.goodArray[indd0].children[indd1].children.count
//            }  else  {
//                return 0
//            }
            
        }
       
        
     
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        
        if self.showingGoodsIndex.isSome {
           self.itemArray[indexPath.row].selectX =  !self.itemArray[indexPath.row].selectX
            self.tableView.reloadData()

          
        } else {
            var currentModel:GoodTreeNode!
            if self.selectDeepIndex == -1 {
                currentModel = self.goodArray[indexPath.row]
                self.selectMark[0] = (indexPath.row,self.goodArray[indexPath.row])
                
            } else {
                currentModel = showNode?.children[indexPath.row]
                
                self.selectMark[self.selectDeepIndex + 1] = (indexPath.row, currentModel)
            }
//            else if self.selectDeepIndex == 0 {
//                let indd0 = self.selectMark[0]!.0
//                let model = self.goodArray[indd0].children[indexPath.row]
//                currentModel = model
//                
//                self.selectMark[1] = (indexPath.row,model)
//                
//                
//            } else if self.selectDeepIndex == 1 {
//                let indd0 = self.selectMark[0]!.0
//                let indd1 = self.selectMark[1]!.0
//                let model = self.goodArray[indd0].children[indd1].children[indexPath.row]
//                currentModel = model
//                
//                self.selectMark[2] = (indexPath.row,model)
//                
//            }
            self.selectDeepIndex += 1
            
            if currentModel.s_last_node == "1" {
               

                
                self.showingGoodsIndex = self.selectDeepIndex
                
                KSLog("lllllll")
                KSLog(self.showingGoodsIndex)
                self.getGoods(model: currentModel)
            } else {
                
                self.configZyaClaBtnView()
                self.tableView.reloadData()
            }
        }
        
      
        
        
       
        
    }
    
}






import ObjectMapper
struct GoodTreeNode: Mappable {
   
   var id_key:String?
    var s_name:String?
    var s_last_node:String?
    var children = [GoodTreeNode]()
   init?(map: Map) {
       
   }
   // Mappable
   mutating func mapping(map: Map) {
       id_key <-  (map["id_key"],StringTransform())
       s_name <-  (map["s_name"],StringTransform())
       s_last_node <-  (map["s_last_node"],StringTransform())
       children <-  map["children"]

   }
}
